<?php
$userName = isset($_POST['username']) ? $_POST['username'] : "";
$pw = isset($_POST['pw']) ? $_POST['pw'] : "";
$rememberMe = isset($_POST['rememberMe']) ? $_POST['rememberMe'] : "";
if($userName == "" or $pw == ""){
    $a['error'] = 1;
    $a['errMsg'] = "用户名和密码必须填写！";
    echo json_encode($a);
    exit;
}
include_once ("conn.php");
$postLogin = new Bbs();
$result = $postLogin -> login($userName,$pw);

if($result['error'] == 0 ){
    if($result['rowNum']){//登录成功
        session_start();
        $info = $result['info'];
        $_SESSION['loginUser'] = $userName;
        $_SESSION['admin'] = $info['admin'];
        $_SESSION['loginUserID'] = $info['id'];
        //如果登录时，用户有选择保存登录，则写入COOKIE  默认有限期为7天
        if($rememberMe){
            setcookie('hasLoggedUserName',$userName,time() + 7*24*3600);
        }
        else{
            setcookie('hasLoggedUserName','',time() - 100);
        }
        $a['error'] = 0;
        $a['username'] = $userName;
        $a['nickname'] = $info['nickname'];
        $a['admin'] = $info['admin'];
        $a['pic'] = $info['pic'];
        $a['singUpDate'] = $info['postDate'];
        //读取当前用户最后发贴时间以及发贴数量
        $result = $postLogin->topic('maintopic',$_SESSION['loginUserID']);
        if($result['error'] == 0 and $result['rowCount']){
            $a['lastTitle'] = $result['info']['title'];
            $a['lastPostTime'] = $result['info']['posttime'];
            $a['total'] = $result['rowCount'];
            //更新当前用户等级
            $sql = "select gradename from grade where topicsnum >=".$result['rowCount'] ." order by id limit 1";
            $result1 = $postLogin -> query($sql);
            $gradename = $result1['result'][0]['gradename'];
            //判断当前等级是否改变
            if($gradename != $info['grade']){  //说明等级有变化，则更新之
                $result = $postLogin -> update("userinfo",0,"id=".$info['id'],$gradename,"grade");
            }
        }
        else{
            $a['lastTitle'] = '暂未发贴';
            $a['lastPostTime'] = '暂未发贴';
            $a['total'] = '暂未发贴';
        }
        $result = $postLogin->topic('subtopic',$_SESSION['loginUserID']);
        if($result['error'] == 0 and $result['rowCount']){
            $a['lastReplyTime'] = $result['info']['posttime'];
        }
        else{
            $a['lastReplyTime'] = '暂未回复';
        }
    }
    else{  //登录失败
        session_destroy();
        setcookie('hasLoggedUserName','',time() - 100);
        $a['error'] = 1;
        $a['errMsg'] = "登录失败";
    }
}
else{ //查询出错
    $a['error'] = 1;
    $a['errMsg'] = "查询出错";
}
echo json_encode($a);